package cn.kgc.springmvcday04.intercepters;

import cn.kgc.springmvcday04.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author 课工场
 * @date 2023/10/18
 * @description    非法请求的拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    // 目标方法之前执行  /user/add    -> LoginInterceptor  preHandle  -> true  放行   false  拦截

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("---------------LoginInterceptor--------------------");

        // 从会话对象中获取用户信息 判定用户是否登录
        HttpSession session = request.getSession();
        User  user = (User) session.getAttribute("user");
        System.out.println("user = " + user);

        if (user==null){   //  当前用户没有登录 需要跳转登录页

            session.setAttribute("info","请登录后访问");
            // 将页面重定向到登录页
            response.sendRedirect(request.getContextPath()+"/login.jsp");
            return  false;
        }

        return  true;
    }
}
